/*
 *    This file is part of SSHTunneler.
 *
 *    Copyright 2009 Jean-Sebastien Gelinas <calestar@gmail.com>
 *
 *    SSHTunneler is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    SSHTunneler is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with SSHTunneler.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package sshtunneler.client.data;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jdom.JDOMException;

import sshtunneler.client.SSHTunnelerApp;
import sshtunneler.library.ServerTunnelFile;

public class TunnelerServerTunnelFile extends
		sshtunneler.library.ServerTunnelFile<TunnelerServer> {

	private TunnelerServerTunnelFile() {
	}

	public static final TunnelerServerTunnelFile inst = new TunnelerServerTunnelFile();

	public void auto_save() {
		try {
			this.save(TunnelerServerTunnelFile.getDefaultFile(false),
					TunnelerServerContainer.inst.getServers());
		} catch (IOException ex) {
			Logger.getLogger(SSHTunnelerApp.class.getName()).log(Level.SEVERE,
					null, ex);
		}
	}

	public void auto_load() {
		try {
			List<TunnelerServer> loaded = this.load(TunnelerServerTunnelFile
					.getDefaultFile(true));
			if (loaded != null) {
				Logger.getLogger(SSHTunnelerApp.class.getName()).log(
						Level.INFO, "Loaded default servers/tunnels");
				TunnelerServerContainer.inst.removeAllServers();

				for (TunnelerServer s : loaded) {
					TunnelerServerContainer.inst.addServer(s);
				}
			}
		} catch (JDOMException ex) {
			Logger.getLogger(SSHTunnelerApp.class.getName()).log(Level.SEVERE,
					null, ex);
		} catch (IOException ex) {
			Logger.getLogger(SSHTunnelerApp.class.getName()).log(Level.SEVERE,
					null, ex);
		}
	}

	private static File getDefaultFile(boolean must_exist) {
		String home_path = System.getProperty("user.home");
		String default_file_name = "SSHTunneler_Default"
				+ ServerTunnelFile.extension;
		if (home_path == null) {
			return null;
		}

		if (!home_path.endsWith(File.separator)) {
			home_path = home_path + File.separator;
		}

		String file_path = home_path + default_file_name;
		File file = new File(file_path);
		if (must_exist && !file.exists()) {
			return null;
		}
		return file;
	}

	@Override
	public TunnelerServer createServer(String username, String hostname,
			int port) {
		return new TunnelerServer(username, hostname, port);
	}

}
